﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using BrokerBase.Lib.Product;

namespace Broker.View.ViewModel
{
    public class ProductNameModel
    {

        public static IList<ProductNameModel> LoadBySQL(string sql)
        {
            using (ISession sess = LibGlobal.HbmSessionFactory.OpenSession())
            {
                IList<ProductNameModel> ls = new List<ProductNameModel>(100);

                IList<object[]> qls = sess.CreateSQLQuery(sql).List<object[]>();

                foreach (object[] obj in qls)
                {
                    ProductNameModel pm = new ProductNameModel();
                    pm.Id = Convert.ToInt32(obj[0]);
                    pm.Name = Convert.ToString(obj[1]);
                    pm.ProductType = (ProductType)Convert.ToInt32(obj[2]);
                    pm.CompanyId = Convert.ToInt32(obj[3]);
                    pm.CompanyName = obj[4].ToString();
                    ls.Add(pm);
                }

                return ls;
            }
        }

        public static IList<ProductNameModel> LoadByLikeName(string likeName)
        {
            string sql="select p.Id as ProductId,p.Name as ProductName,p.ProductType as ProductType,c.Id as CompanyId,c.Name as CompanyName from Product as p left join Company as c on p.Companyid=c.Id";

            if (!string.IsNullOrEmpty(likeName))
                sql += " where p.Name like '%" + likeName + "%'";

            return LoadBySQL(sql);
        }

        public static IList<ProductNameModel> LoadAllBasic(int companyId)
        {
            string sql = "select p.Id as ProductId,p.Name as ProductName,p.ProductType as ProductType,c.Id as CompanyId,c.Name as CompanyName from Product as p left join Company as c on p.Companyid=c.Id   where p.ProductType=1";

            string order = null;

            if (LibGlobal.AppType == AppType.Business)
                order = " order by c.Name collate PinYin,p.Name collate PinYin";
            else
                order = " order by c.Name";

            if (companyId > 0)
                sql += " and companyid=" + companyId;

            sql += order;

            return LoadBySQL(sql);

        }


        public int Id { get; set; }

        public string Name { get; set; }

        public string CompanyName { get; set; }

        public int CompanyId { get; set; }
       
        public ProductType ProductType { get; set; }

        
    }
}
